package com.example.demo.service.impl;

import com.example.demo.model.Category;
import com.example.demo.model.Drink;
import com.example.demo.repository.CategoryRepository;
import com.example.demo.repository.DrinkRepository;
import com.example.demo.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;
    @Autowired
    public DrinkRepository drinkRepository;
    @Override
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }


    @Override
    public void updateCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public void addNewCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategoryById(Integer id) {
        // 2. 更新所有和该category关联的drink
        // 2.1 通过category_id把关联的drink查询出来
        List<Drink> drinks = drinkRepository.findDrinksByCategory_Id(id);

        for (Drink drink : drinks) {
            // 2.2 把这些drink的category设置为空
            drink.setCategory(null);

            // 2.3 保存
            drinkRepository.save(drink);
        }

        // 1. 删除指定id的category
        categoryRepository.deleteById(id);

    }


}
